package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-gin-admin/global"
	"github.com/go-gin-admin/util"
	"github.com/minio/minio-go/v6"
	"net/http"
	"net/url"
	"time"
)

func Upload(c *gin.Context) {
	var uploadFile global.UploadFile
	// 获取上传的form
	file, _ := c.FormFile("file")
	uploadFile.FileName = file.Filename
	uploadFile.FileSize = file.Size
	uploadFile.ContentType = file.Header.Get("Content-Type")
	open, err := file.Open()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("上传失败"))
		return
	}
	// 上传
	_, err = global.MinioClient.PutObject(global.MyMinio.BucketName, uploadFile.FileName, open, uploadFile.FileSize, minio.PutObjectOptions{ContentType: uploadFile.ContentType})
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("上传失败"))
		return
	}
	// 请求参数
	reqParams := make(url.Values)

	// 生成一个有效期为1天的预览地址
	presignedURL, err := global.MinioClient.PresignedGetObject(global.MyMinio.BucketName, uploadFile.FileName, time.Second*24*60*60, reqParams)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("上传失败"))
		return
	}
	url := getFileUrl(presignedURL)
	m := make(map[string]interface{})
	m["uri"] = url
	m["fileName"] = uploadFile.FileName
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 拼接预览的文件地址
func getFileUrl(u *url.URL) string {
	url := fmt.Sprintf("%s://%s%s?%s", u.Scheme, u.Host, u.Path, u.RawQuery)
	return url
}
